<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-05-26
 * Time: 23:02:12
 * Info:
 */

namespace app;

class Request extends \support\Request
{

    public function isPost()
    {
        $getMethod = Request::method();
        if ($getMethod == 'POST') {
            return true;
        }

        return false;
    }

    public function isGet()
    {
        $getMethod = Request::method();
        if ($getMethod == 'GET') {
            return true;
        }

        return false;
    }

    public function input($name = null, $default = null)
    {
        return $this->filter(parent::input($name, $default));
    }

    public function get($name = null, $default = null)
    {
        return $this->filter(parent::get($name, $default));
    }

    public function post($name = null, $default = null)
    {
        return $this->filter(parent::post($name, $default));
    }

    public function all($name = null, $default = null)
    {
        return $this->filter(parent::all($name, $default));
    }

    public function filter($value)
    {
        if ( ! $value) {
            return $value;
        }
        if (is_array($value)) {
            array_walk_recursive($value, function (&$item) {
                if (is_string($item)) {
                    $item = htmlspecialchars($item);
                }
            });
        } else {
            $value = htmlspecialchars($value);
        }

        return $value;
    }

    /**
     * 生成token令牌
     *
     * @param string $name
     * @param        $type
     *
     * @return string
     */
    public function buildToken(string $name = '__huicmf_token__', $type = 'md5'): string
    {
        $type  = is_callable($type) ? $type : 'md5';
        $str   = request()->controller.'-'.request()->action.'-'.date('Y-m-d').uniqid();
        $token = call_user_func($type, $str);

        session()->set($name, $token);

        return $token;
    }

    /**
     * 检查请求令牌
     * @access public
     *
     * @param string $token 令牌名称
     * @param array  $data  表单数据
     *
     * @return bool
     * 验证方式：
     * $checkToken = $request->checkToken($params);
     * if (false === $checkToken) {
     * return error_json('invalid token');
     * }
     */
    public function checkToken(array $data = [], string $token = '__huicmf_token__'): bool
    {
        if ( ! session()->has($token)) {
            // 令牌数据无效
            return false;
        }

        if (empty($data)) {
            $data = request()->post();
        }

        // 令牌验证
        if (isset($data[$token]) && session()->get($token) === $data[$token]) {
            // 防止重复提交
            session()->delete($token); // 验证完成销毁session

            return true;
        }

        // 开启TOKEN重置
        session()->delete($token);

        return false;
    }

}
